clear all 
set more off

*****************************************************************************
******************** SECTOR LEVEL REGRESSIONS *******************************
*****************************************************************************

// Load data created in setup_data_4.R 
use "..\data\sectors_unbalanced.dta", clear 

// Create and format date variable 
gen date = yq(year, quarter) 
format date %tq

// Collapse by 2-digit sector
tostring naics_code, gen(naics6) 
gen naics2 = substr(naics6,1,2) 
collapse (sum) sector_quarter_obligations, by(naics2 date) 

// Create numerical firm identifier
egen sector_id = group(naics2)
tsset sector_id date

// Generate 4-quarter lag obligations variable and 4-quarter growth rate
gen log_obligations = log(sector_quarter_obligations) 
label var log_obligations "Log Purchases"

eststo clear 
eststo: reg log_obligations L4.log_obligations i.sector_id if date < yq(2020,1)
eststo: reg log_obligations L4.log_obligations i.sector_id i.date if date < yq(2020,1)


*****************************************************************************
******************** FIRM LEVEL REGRESSIONS *********************************
*****************************************************************************

// Load data created in setup_data_4.R 
use "..\data\firms_unbalanced.dta", clear 

// Create and format date variable 
gen date = yq(year, quarter) 
format date %tq

// Create numerical firm identifier
egen firm_id = group(recipient_parent_duns)
tsset firm_id date

// Select top K and Q firms based on lifetime obligations 
preserve 
tempfile ranking
collapse (sum) firm_quarter_obligations, by(recipient_parent_duns firm_id top10 top1000) 
egen firm_rank = rank(-firm_quarter_obligations) if recipient_parent_duns != "NA" 

local K 100

gen top_K = firm_rank <= `K'
keep firm_id firm_rank top_K
save `ranking' 

restore 

merge m:1 firm_id using `ranking'

// Fill panel so it is balanced
keep if top_K == 1
keep firm_id date firm_quarter_obligations 

// Generate 4-quarter lag obligations variable and 4-quarter growth rate
gen log_obligations = log(firm_quarter_obligations) 

sort firm_id date
label var log_obligations "Log Purchases"
 
eststo: reg log_obligations L4.log_obligations i.firm_id if date < yq(2020,1)
eststo: reg log_obligations L4.log_obligations i.firm_id i.date if date < yq(2020,1)


esttab using "../output/Table2_lower.tex", se replace r2 b(%4.3f) label collabels(none) nocons indicate("Sector FEs = *sector_id*" "Firm FEs = *firm_id*" "Time FEs = *date*") compress mtitle("\shortstack{g_t \\ (Sectors)}" "\shortstack{ g_t \\ (Sectors)}" "\shortstack{g_t \\ (Firms)}" "\shortstack{g_t \\ (Firms)}")
